/**
 * 团队页面JavaScript功能
 */

class TeamPage {
    constructor() {
        this.apiBaseUrl = '/api/team_api.php';
        this.init();
    }

    init() {
        this.bindEvents();
        this.initTooltips();
        this.loadData();
    }

    bindEvents() {
        // 复制邀请码
        const copyInviteBtn = document.querySelector('[data-action="copy-invite"]');
        if (copyInviteBtn) {
            copyInviteBtn.addEventListener('click', () => this.copyInviteCode());
        }

        // 复制邀请链接
        const copyLinkBtn = document.querySelector('[data-action="copy-link"]');
        if (copyLinkBtn) {
            copyLinkBtn.addEventListener('click', () => this.copyInviteLink());
        }

        // 下载二维码
        const downloadBtn = document.querySelector('[data-action="download-qr"]');
        if (downloadBtn) {
            downloadBtn.addEventListener('click', () => this.downloadQRCode());
        }

        // 刷新二维码
        const refreshBtn = document.querySelector('[data-action="refresh-qr"]');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => this.refreshQRCode());
        }



        // 复制二维码链接
        const copyQrUrlBtn = document.querySelector('[data-action="copy-qr-url"]');
        if (copyQrUrlBtn) {
            copyQrUrlBtn.addEventListener('click', () => this.copyQRUrl());
        }

        // 返回按钮
        const backBtn = document.querySelector('[data-action="back"]');
        if (backBtn) {
            backBtn.addEventListener('click', () => this.goBack());
        }
    }

    initTooltips() {
        // 初始化工具提示
        const tooltipElements = document.querySelectorAll('[data-tooltip]');
        tooltipElements.forEach(element => {
            element.addEventListener('mouseenter', this.showTooltip);
            element.addEventListener('mouseleave', this.hideTooltip);
        });
    }

    showTooltip(event) {
        const tooltip = document.createElement('div');
        tooltip.className = 'tooltip';
        tooltip.textContent = event.target.getAttribute('data-tooltip');
        tooltip.style.cssText = `
            position: absolute;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 1000;
            pointer-events: none;
            white-space: nowrap;
        `;
        
        document.body.appendChild(tooltip);
        
        const rect = event.target.getBoundingClientRect();
        tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
        tooltip.style.top = rect.top - tooltip.offsetHeight - 8 + 'px';
        
        event.target._tooltip = tooltip;
    }

    hideTooltip(event) {
        if (event.target._tooltip) {
            event.target._tooltip.remove();
            delete event.target._tooltip;
        }
    }

    // 复制邀请码
    async copyInviteCode() {
        const inviteCode = document.querySelector('[data-invite-code]')?.textContent?.trim();
        if (!inviteCode) {
            this.showToast('邀请码未找到', 'error');
            return;
        }

        try {
            await this.copyToClipboard(inviteCode);
            this.showToast('邀请码已复制到剪贴板！', 'success');
        } catch (error) {
            console.error('复制失败:', error);
            this.showToast('复制失败，请手动复制', 'error');
        }
    }

    // 复制邀请链接
    async copyInviteLink() {
        const inviteLink = document.getElementById('invite-link')?.value;
        if (!inviteLink) {
            this.showToast('邀请链接未找到', 'error');
            return;
        }

        try {
            await this.copyToClipboard(inviteLink);
            this.showToast('邀请链接已复制到剪贴板！', 'success');
        } catch (error) {
            console.error('复制失败:', error);
            this.showToast('复制失败，请手动复制', 'error');
        }
    }

    // 通用复制到剪贴板方法
    async copyToClipboard(text) {
        if (navigator.clipboard && window.isSecureContext) {
            return await navigator.clipboard.writeText(text);
        } else {
            return this.fallbackCopy(text);
        }
    }

    // 降级复制方案
    fallbackCopy(text) {
        return new Promise((resolve, reject) => {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                document.body.removeChild(textArea);
                if (successful) {
                    resolve();
                } else {
                    reject(new Error('复制命令失败'));
                }
            } catch (err) {
                document.body.removeChild(textArea);
                reject(err);
            }
        });
    }

    // 下载二维码
    async downloadQRCode() {
        const qrImage = document.getElementById('qr-code-image');
        if (!qrImage) {
            this.showToast('二维码图片未找到', 'error');
            return;
        }

 

        try {
            const canvas = await this.imageToCanvas(qrImage);
            const blob = await this.canvasToBlob(canvas);
            this.downloadBlob(blob, this.getQRFileName());
            this.showToast('二维码已下载！', 'success');
        } catch (error) {
            console.error('下载失败:', error);
            this.showToast('下载失败', 'error');
        }
    }

    // 图片转Canvas
    imageToCanvas(image) {
        return new Promise((resolve) => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            canvas.width = image.naturalWidth;
            canvas.height = image.naturalHeight;
            
            ctx.drawImage(image, 0, 0);
            resolve(canvas);
        });
    }

    // Canvas转Blob
    canvasToBlob(canvas) {
        return new Promise((resolve, reject) => {
            canvas.toBlob((blob) => {
                if (blob) {
                    resolve(blob);
                } else {
                    reject(new Error('Canvas转Blob失败'));
                }
            }, 'image/png');
        });
    }

    // 下载Blob
    downloadBlob(blob, filename) {
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 获取二维码文件名
    getQRFileName() {
        const username = document.querySelector('[data-username]')?.textContent?.trim() || 'user';
        const inviteCode = document.querySelector('[data-invite-code]')?.textContent?.trim() || 'code';
        return `邀请二维码_${username}_${inviteCode}.png`;
    }

    // 刷新二维码
    async refreshQRCode() {
        try {
            // 获取当前的邀请链接
            const inviteLink = document.getElementById('invite-link')?.value;
            if (!inviteLink) {
                this.showToast('邀请链接未找到', 'error');
                return;
            }
            
            // 使用新的生成方法重新生成二维码
            await this.updateQRCode(inviteLink, {
                size: 300,
                errorCorrection: 'L',
                margin: 4,
                moduleSize: 3
            });
            
        } catch (error) {
            console.error('刷新二维码失败:', error);
            this.showToast('二维码刷新失败', 'error');
        }
    }



    // 降级分享方案
    async fallbackShare(shareData) {
        const shareText = `${shareData.text}\n注册链接：${shareData.url}`;
        
        try {
            await this.copyToClipboard(shareText);
            this.showToast('分享内容已复制到剪贴板！', 'success');
        } catch (error) {
            console.error('分享失败:', error);
            this.showToast('分享失败', 'error');
        }
    }

    // 返回上一页
    goBack() {
        if (window.history.length > 1) {
            window.history.back();
        } else {
            window.location.href = '/';
        }
    }

    // 显示提示消息
    showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        
        const colors = {
            success: '#28a745',
            error: '#dc3545',
            warning: '#ffc107',
            info: '#17a2b8'
        };
        
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${colors[type] || colors.info};
            color: white;
            padding: 15px 25px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 10000;
            max-width: 300px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
            transform: translateX(100%);
            transition: transform 0.3s ease;
        `;
        
        document.body.appendChild(toast);
        
        // 显示动画
        setTimeout(() => {
            toast.style.transform = 'translateX(0)';
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }

    // 检测是否为移动端
    isMobile() {
        return /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    // 显示加载状态
    showLoading(element) {
        if (element) {
            element.classList.add('loading');
        }
    }

    // 隐藏加载状态
    hideLoading(element) {
        if (element) {
            element.classList.remove('loading');
        }
    }

    // 显示错误消息
    showError(message, container) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        errorDiv.textContent = message;
        
        if (container) {
            container.insertBefore(errorDiv, container.firstChild);
        } else {
            document.body.appendChild(errorDiv);
        }
        
        // 5秒后自动隐藏
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.parentNode.removeChild(errorDiv);
            }
        }, 5000);
    }

    // 显示成功消息
    showSuccess(message, container) {
        const successDiv = document.createElement('div');
        successDiv.className = 'success-message';
        successDiv.textContent = message;
        
        if (container) {
            container.insertBefore(successDiv, container.firstChild);
        } else {
            document.body.appendChild(successDiv);
        }
        
        // 3秒后自动隐藏
        setTimeout(() => {
            if (successDiv.parentNode) {
                successDiv.parentNode.removeChild(successDiv);
            }
        }, 3000);
    }

    // 加载数据
    async loadData() {
        try {
            await this.loadTeamStats();
            await this.loadTeamMembers();
            await this.loadCommissions();
        } catch (error) {
            console.error('加载数据失败:', error);
            this.showToast('数据加载失败', 'error');
        }
    }

    // 加载团队统计
    async loadTeamStats() {
        try {
            const response = await this.apiCall('get_stats');
            if (response.success) {
                this.updateTeamStats(response.data);
            }
        } catch (error) {
            console.error('加载团队统计失败:', error);
        }
    }

    // 加载团队成员
    async loadTeamMembers() {
        try {
            const response = await this.apiCall('get_members');
            if (response.success) {
                this.updateTeamMembers(response.data);
            }
        } catch (error) {
            console.error('加载团队成员失败:', error);
        }
    }

    // 加载分成记录
    async loadCommissions() {
        try {
            const response = await this.apiCall('get_commissions');
            if (response.success) {
                this.updateCommissions(response.data);
            }
        } catch (error) {
            console.error('加载分成记录失败:', error);
        }
    }

    // API调用
    async apiCall(action, data = {}) {
        const url = new URL(this.apiBaseUrl);
        url.searchParams.append('action', action);
        
        const options = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        };

        if (Object.keys(data).length > 0) {
            options.method = 'POST';
            options.body = JSON.stringify(data);
        }

        const response = await fetch(url, options);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    }

    // 更新团队统计
    updateTeamStats(stats) {
        const teamSizeEl = document.querySelector('.stat-card:nth-child(1) .stat-value');
        const totalEarnedEl = document.querySelector('.stat-card:nth-child(2) .stat-value');
        const totalPaidEl = document.querySelector('.stat-card:nth-child(3) .stat-value');
        
        if (teamSizeEl) teamSizeEl.textContent = stats.team_size;
        if (totalEarnedEl) totalEarnedEl.textContent = `¥${this.formatNumber(stats.total_commission_earned)}`;
        if (totalPaidEl) totalPaidEl.textContent = `¥${this.formatNumber(stats.total_commission_paid)}`;
    }

    // 更新团队成员
    updateTeamMembers(members) {
        // 这里可以实现动态更新团队成员列表
        console.log('团队成员数据已更新:', members);
    }

    // 更新分成记录
    updateCommissions(commissions) {
        // 这里可以实现动态更新分成记录
        console.log('分成记录数据已更新:', commissions);
    }

    // 格式化数字
    formatNumber(num) {
        return new Intl.NumberFormat('zh-CN', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(num);
    }

    // 刷新页面数据
    async refreshData() {
        this.showToast('正在刷新数据...', 'info');
        try {
            await this.loadData();
            this.showToast('数据刷新成功', 'success');
        } catch (error) {
            console.error('刷新数据失败:', error);
            this.showToast('数据刷新失败', 'error');
        }
    }

    // 复制二维码链接
    async copyQRUrl() {
        const qrUrlElement = document.querySelector('[data-qr-url]');
        if (!qrUrlElement) {
            this.showToast('二维码链接未找到', 'error');
            return;
        }

        const qrUrl = qrUrlElement.textContent.trim();
        if (!qrUrl) {
            this.showToast('二维码链接为空', 'error');
            return;
        }

        try {
            await this.copyToClipboard(qrUrl);
            this.showToast('二维码链接已复制到剪贴板！', 'success');
        } catch (error) {
            console.error('复制失败:', error);
            this.showToast('复制失败，请手动复制', 'error');
        }
    }

    // 更新二维码状态
    updateQRStatus(status, message) {
        const statusIndicator = document.getElementById('qr-status-indicator');
        if (!statusIndicator) return;

        const statusDot = statusIndicator.querySelector('.status-dot');
        const statusText = statusIndicator.querySelector('.status-text');
        
        if (statusText) {
            statusText.textContent = message;
        }

        // 更新状态样式
        statusIndicator.className = 'status-indicator';
        if (status === 'success') {
            statusIndicator.classList.add('status-success');
        } else if (status === 'error') {
            statusIndicator.classList.add('status-error');
        } else if (status === 'loading') {
            statusIndicator.classList.add('status-loading');
        }
    }

    // 生成二维码并返回base64
    async generateQRCodeBase64(text, options = {}) {
        const defaultOptions = {
            size: 300,
            errorCorrection: 'L',
            margin: 4,
            moduleSize: 3
        };
        
        const config = { ...defaultOptions, ...options };
        
        try {
            // 更新状态为加载中
            this.updateQRStatus('loading', '正在生成二维码...');
            
            // 调用后端API生成二维码
            const response = await fetch('/api/generate_qr.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    text: text,
                    size: config.size,
                    error_correction: config.errorCorrection,
                    margin: config.margin,
                    module_size: config.moduleSize
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            
            if (result.success && result.data && result.data.base64) {
                // 验证base64数据
                const base64Data = result.data.base64;
                if (this.validateBase64Image(base64Data)) {
                    this.updateQRStatus('success', '二维码生成成功');
                    return base64Data;
                } else {
                    throw new Error('生成的base64数据无效');
                }
            } else {
                throw new Error(result.error || '二维码生成失败');
            }
            
        } catch (error) {
            console.error('生成二维码失败:', error);
            this.updateQRStatus('error', '二维码生成失败');
            throw error;
        }
    }

    // 验证base64图片数据
    validateBase64Image(base64Data) {
        try {
            // 检查base64格式
            if (!base64Data || typeof base64Data !== 'string') {
                return false;
            }
            
            // 检查是否包含data URI前缀
            if (base64Data.startsWith('data:image/')) {
                // 提取base64部分
                const base64Part = base64Data.split(',')[1];
                if (!base64Part) {
                    return false;
                }
                
                // 尝试解码
                const binaryString = atob(base64Part);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                
                // 检查PNG文件头
                return this.isValidPNGHeader(bytes);
            } else {
                // 直接base64数据
                const binaryString = atob(base64Data);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                
                return this.isValidPNGHeader(bytes);
            }
        } catch (error) {
            console.error('验证base64数据失败:', error);
            return false;
        }
    }

    // 检查PNG文件头
    isValidPNGHeader(bytes) {
        if (bytes.length < 8) {
            return false;
        }
        
        // PNG文件头: 89 50 4E 47 0D 0A 1A 0A
        const pngHeader = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
        
        for (let i = 0; i < 8; i++) {
            if (bytes[i] !== pngHeader[i]) {
                return false;
            }
        }
        
        return true;
    }

    // 使用Canvas生成二维码base64（备用方案）
    async generateQRCodeWithCanvas(text, options = {}) {
        const defaultOptions = {
            size: 300,
            backgroundColor: '#FFFFFF',
            foregroundColor: '#000000'
        };
        
        const config = { ...defaultOptions, ...options };
        
        try {
            // 创建一个简单的二维码图案（这里只是示例，实际应该使用专业的二维码库）
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            canvas.width = config.size;
            canvas.height = config.size;
            
            // 填充背景
            ctx.fillStyle = config.backgroundColor;
            ctx.fillRect(0, 0, config.size, config.size);
            
            // 绘制简单的二维码图案（这里只是示例）
            ctx.fillStyle = config.foregroundColor;
            const moduleSize = 10;
            const modules = Math.floor(config.size / moduleSize);
            
            // 生成简单的伪随机图案
            for (let x = 0; x < modules; x++) {
                for (let y = 0; y < modules; y++) {
                    // 使用文本内容生成伪随机图案
                    const hash = this.simpleHash(text + x + y);
                    if (hash % 2 === 0) {
                        ctx.fillRect(x * moduleSize, y * moduleSize, moduleSize, moduleSize);
                    }
                }
            }
            
            // 转换为base64
            const base64 = canvas.toDataURL('image/png');
            return base64;
            
        } catch (error) {
            console.error('Canvas生成二维码失败:', error);
            throw error;
        }
    }

    // 简单哈希函数
    simpleHash(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        return Math.abs(hash);
    }

    // 动态更新二维码
    async updateQRCode(text, options = {}) {
        try {
            const qrImage = document.getElementById('qr-code-image');
            if (!qrImage) {
                throw new Error('二维码图片元素未找到');
            }
            
            // 生成新的二维码
            const base64Data = await this.generateQRCodeBase64(text, options);
            
            // 更新图片源
            qrImage.src = base64Data;
            
            // 更新相关信息
            this.updateQRInfo(text);
            
            this.showToast('二维码已更新', 'success');
            
        } catch (error) {
            console.error('更新二维码失败:', error);
            this.showToast('二维码更新失败', 'error');
        }
    }

    // 更新二维码信息
    updateQRInfo(text) {
        // 更新二维码链接信息
        const qrUrlElement = document.querySelector('[data-qr-url]');
        if (qrUrlElement) {
            qrUrlElement.textContent = text;
        }
        
        // 更新邀请链接输入框
        const inviteLinkInput = document.getElementById('invite-link');
        if (inviteLinkInput) {
            inviteLinkInput.value = text;
        }
    }

    // 批量生成二维码
    async generateMultipleQRCodes(texts, options = {}) {
        const results = [];
        
        for (let i = 0; i < texts.length; i++) {
            try {
                const base64 = await this.generateQRCodeBase64(texts[i], options);
                results.push({
                    text: texts[i],
                    base64: base64,
                    success: true
                });
            } catch (error) {
                results.push({
                    text: texts[i],
                    error: error.message,
                    success: false
                });
            }
        }
        
        return results;
    }

    // 测试二维码生成功能
    async testQRGeneration() {
        const testTexts = [
            'Hello World',
            'http://154.92.15.189/',
            '测试中文内容',
            '邀请码：TEST1234'
        ];
        
        this.showToast('开始测试二维码生成...', 'info');
        
        try {
            const results = await this.generateMultipleQRCodes(testTexts, {
                size: 200,
                errorCorrection: 'L',
                margin: 4,
                moduleSize: 3
            });
            
            let successCount = 0;
            let failCount = 0;
            
            results.forEach(result => {
                if (result.success) {
                    successCount++;
                    console.log(`✓ 成功生成: ${result.text}`);
                } else {
                    failCount++;
                    console.error(`✗ 生成失败: ${result.text} - ${result.error}`);
                }
            });
            
            this.showToast(`测试完成: 成功 ${successCount} 个，失败 ${failCount} 个`, 
                failCount === 0 ? 'success' : 'warning');
            
            return results;
            
        } catch (error) {
            console.error('测试二维码生成失败:', error);
            this.showToast('测试失败', 'error');
            throw error;
        }
    }

    // 获取二维码信息
    getQRCodeInfo(base64Data) {
        try {
            if (!base64Data) {
                return null;
            }
            
            let base64Part = base64Data;
            if (base64Data.startsWith('data:image/')) {
                base64Part = base64Data.split(',')[1];
            }
            
            const binaryString = atob(base64Part);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            
            return {
                size: bytes.length,
                isValidPNG: this.isValidPNGHeader(bytes),
                base64Length: base64Part.length,
                dataUri: base64Data.startsWith('data:image/')
            };
            
        } catch (error) {
            console.error('获取二维码信息失败:', error);
            return null;
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new TeamPage();
});

// 导出类供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = TeamPage;
}
